import DatabaseConnection from "./DatabaseConnection";
import LogFactory from "log/LogFactory";

const log = LogFactory.getLogger("IndexedDBStorage");
/**
 * IndexedDBStorage本地存储类,此类会从本地的localStorage中获取用户登录的用户名信息
 * @param T 存储数据类型
 */
export default class IndexedDBStorage<T> {
    private readonly databaseConnection: DatabaseConnection;
    private readonly tableName: string;

    /**
     * 构造函数
     * @param connect 数据库连接对象
     * @param tableName 需要操作数据表名字
     */
    constructor(connect: DatabaseConnection, tableName: string) {
        this.databaseConnection = connect;
        this.tableName = tableName;
    }
    /**
     * 保存数据到IndexedDB
     * @param data 保存的数据
     */
    public async saveData(data: T){
        log.debug("保存数据到IndexedDBStorage", data);
        const db = await this.databaseConnection.getConnection();
        const request = db.transaction(this.tableName, "readwrite").objectStore(this.tableName).put(data);
        request.onsuccess = (event) => {
          log.debug("保存数据成功", event);
        };
        request.onerror = (event) => {
            log.error("保存数据失败", event);
        };
    }

    /**
     * 从IndexedDB中获取数据,数据来源为当前登录用户的用户名
     */
    public async getData(): Promise<T | null> {
        const username = window.localStorage.getItem("username");
        // log.debug("从IndexedDB中获取数据", this.tableName, "username");
        if (!username){
            log.error("没有找到username");
            return Promise.resolve(null);
        }
        const db = await this.databaseConnection.getConnection();
        const store = db.transaction(this.tableName, "readonly").objectStore(this.tableName);
        return new Promise((resolve, reject) => {
            const request = store.get(username);
            request.onsuccess = (event: any) => {
                // log.debug("查找数据成功", event.target.result);
                resolve(event.target.result);
            };
            request.onerror = (event: Event) => {
                log.error("查找数据失败", event);
                reject(event);
            };
        });
    }
}